import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/reg_utils.dart';
import 'package:guochaoapp/controller/mine/mine_controller.dart';
import 'package:guochaoapp/controller/shopping/shopping_controller.dart';
import 'package:guochaoapp/model/user_entity.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';
//import 'package:throttling/throttling.dart';

class GCLoginController extends GetxController {
  UserService userService = Get.find();

  final GlobalKey passwordLoginFormKey = GlobalKey<FormState>();
  final GlobalKey smsLoginFormKey = GlobalKey<FormState>();
  final loginAccount = "".obs;
  final password = "".obs;
  final securePassword = true.obs;

  final smsLogin = false.obs;

  final phone = "".obs;
  final randomCode = "".obs;

  Timer timer;
  final countDownTime = 0.obs;
  final count1 = 0;

  closeAction() {
    Get.offAllNamed(Routes.INITIAL);
  }

  changeLogin() {
    smsLogin.toggle();
    // this.loginAccount.value = this.password.value = this.phone.value = this.randomCode.value = "";
  }

  forgetPassword() {
    Get.toNamed(Routes.FORGET_PASSWORD);
  }

  getRandomCode() {
    if (!RegUtils.isChinaPhoneLegal(this.phone.value)) {
      EasyLoading.showError("请输入正确的手机号");
      return;
    }

    if (countDownTime.value > 0) {
      return;
    }

    countDownTime.value = 60;

    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
          countDownTime < 1
              ? timer.cancel()
              : countDownTime.value = countDownTime.value - 1
        };

    timer = Timer.periodic(oneSec, callback);

    HttpClient.request(
        url: SmsApi.randomCode + "/$phone",
        method: Method.PUT,
        onSuccess: (r,_) {
          EasyLoading.showSuccess("发送成功");
        },
        onFailed: (error) {
          EasyLoading.showError(error);
        });
  }

  loginButtonAction() {
    // todo
    submit();
  }

  submit() {
    if (!smsLogin.value) {
      if ((passwordLoginFormKey.currentState as FormState).validate()) {
        var params = {"loginAccount": loginAccount, "oriPassword": password};
        HttpClient.request(
            url: UserApi.login,
            method: Method.POST,
            data: params,
            onSuccess: (r, _) {
              userService.saveUserInfo(UserEntity().fromJson(r["data"]));
              handleSuccessBack();
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }
    } else {
      if ((smsLoginFormKey.currentState as FormState).validate()) {
        var params = {"phone": phone, "randomCode": randomCode};
        HttpClient.request(
            url: UserApi.fastLogin,
            method: Method.POST,
            data: params,
            onSuccess: (r,_) {
              userService.saveUserInfo(UserEntity().fromJson(r["data"]));
              handleSuccessBack();
            },
            onFailed: (error) {
              EasyLoading.showError(error);
            });
      }
    }
  }

  handleSuccessBack() {
    String jump_source = Get.arguments;
    if(jump_source == "shopping") {
      GCShoppingController shopping_c = Get.find();
      shopping_c.refresh();
    } else if(jump_source == "mine"){
      GCMineController mine_c = Get.find();

      if(mine_c != null) {
        mine_c.reqeustMinePageData();
      }
    }
    Get.back();
  }
}
